package com.young.testcoroutine

import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.junit.Test
import kotlin.system.measureTimeMillis

/**
 * Author：young
 * .
 * Time： 2022/9/12 12:29 周一
 * .
 * Desc：组合并发
 */
class CoroutineTest02 {

    /**
     * 同步协程执行两个任务
     */
    @Test
    fun test_sync() = runBlocking {
        val time = measureTimeMillis {
            val one = doOne()
            val two = doTwo()
            println("the result is ${one + two}")
        }

        println("使用了 $time ms")
    }

    /**
     * 组合并发执行两个任务（错误的做法）
     */
    @Test
    fun test_async() = runBlocking {
        val time = measureTimeMillis {
            val one = async { doOne() }.await()
            val two = async { doTwo() }.await()
            println("the result is ${one + two}")
        }

        println("使用了 $time ms")
    }

    private suspend fun doOne(): Int {
        delay(1000)
        return 14
    }

    private suspend fun doTwo(): Int {
        delay(1000)
        return 25
    }

}